<?php
class CartsController extends StoreAppController {
  	var $name = 'StoreCarts';
	var $uses = array('Store.StoreProduct','Store.StoreProductType','Store.StoreDelivery','Store.StoreOrder','Store.StoreOrderDetail','Store.StoreOrderDelivery','User','Customer');
	var $components = array('Auth','Session','Cookie','Password');
	
	var $permissions = array(
		'cart_send' => array('admin','manag','emplo','copyr','users','firms')
	);
	
	var $countrycod = array(
	    "GB"=>"United Kingdom",
	    "AF"=>"Afghanistan",
	    "AX"=>"Aland Islands",
	    "AL"=>"Albania",
	    "DZ"=>"Algeria",
	    "AS"=>"American Samoa",
	    "AD"=>"Andorra",
	    "AO"=>"Angola",
	    "AI"=>"Anguilla",
	    "AQ"=>"Antarctica",
	    "AG"=>"Antigua and Barbuda",
	    "AR"=>"Argentina",
	    "AM"=>"Armenia",
	    "AW"=>"Aruba",
	    "AU"=>"Australia",
	    "AT"=>"Austria",
	    "AZ"=>"Azerbaijan",
	    "BS"=>"Bahamas",
	    "BH"=>"Bahrain",
	    "BD"=>"Bangladesh",
	    "BB"=>"Barbados",
	    "BY"=>"Belarus",
	    "BE"=>"Belgium",
	    "BZ"=>"Belize",
	    "BJ"=>"Benin",
	    "BM"=>"Bermuda",
	    "BT"=>"Bhutan",
	    "BO"=>"Bolivia",
	    "BA"=>"Bosnia and Herzegovina",
	    "BW"=>"Botswana",
	    "BV"=>"Bouvet Island",
	    "BR"=>"Brazil",
	    "IO"=>"British Indian Ocean Territory",
	    "BN"=>"Brunei Darussalam",
	    "BG"=>"Bulgaria",
	    "BF"=>"Burkina Faso",
	    "BI"=>"Burundi",
	    "KH"=>"Cambodia",
	    "CM"=>"Cameroon",
	    "CA"=>"Canada",
	    "CV"=>"Cape Verde",
	    "KY"=>"Cayman Islands",
	    "CF"=>"Central African Republic",
	    "TD"=>"Chad",
	    "CL"=>"Chile",
	    "CN"=>"China",
	    "CX"=>"Christmas Island",
	    "CC"=>"Cocos (Keeling) Islands",
	    "CO"=>"Colombia",
	    "KM"=>"Comoros",
	    "CG"=>"Congo",
	    "CD"=>"Congo, The Democratic Republic of the",
	    "CK"=>"Cook Islands",
	    "CR"=>"Costa Rica",
	    "CI"=>"Côte d'Ivoire",
	    "HR"=>"Croatia",
	    "CU"=>"Cuba",
	    "CY"=>"Cyprus",
	    "CZ"=>"Czech Republic",
	    "DK"=>"Denmark",
	    "DJ"=>"Djibouti",
	    "DM"=>"Dominica",
	    "DO"=>"Dominican Republic",
	    "EC"=>"Ecuador",
	    "EG"=>"Egypt",
	    "SV"=>"El Salvador",
	    "GQ"=>"Equatorial Guinea",
	    "ER"=>"Eritrea",
	    "EE"=>"Estonia",
	    "ET"=>"Ethiopia",
	    "FK"=>"Falkland Islands (Malvinas)",
	    "FO"=>"Faroe Islands",
	    "FJ"=>"Fiji",
	    "FI"=>"Finland",
	    "FR"=>"France",
	    "GF"=>"French Guiana",
	    "PF"=>"French Polynesia",
	    "TF"=>"French Southern Territories",
	    "GA"=>"Gabon",
	    "GM"=>"Gambia",
	    "GE"=>"Georgia",
	    "DE"=>"Germany",
	    "GH"=>"Ghana",
	    "GI"=>"Gibraltar",
	    "GR"=>"Greece",
	    "GL"=>"Greenland",
	    "GD"=>"Grenada",
	    "GP"=>"Guadeloupe",
	    "GU"=>"Guam",
	    "GT"=>"Guatemala",
	    "GG"=>"Guernsey",
	    "GN"=>"Guinea",
	    "GW"=>"Guinea-Bissau",
	    "GY"=>"Guyana",
	    "HT"=>"Haiti",
	    "HM"=>"Heard Island and McDonald Islands",
	    "VA"=>"Holy See (Vatican City State)",
	    "HN"=>"Honduras",
	    "HK"=>"Hong Kong",
	    "HU"=>"Hungary",
	    "IS"=>"Iceland",
	    "IN"=>"India",
	    "ID"=>"Indonesia",
	    "IR"=>"Iran, Islamic Republic of",
	    "IQ"=>"Iraq",
	    "IE"=>"Ireland",
	    "IM"=>"Isle of Man",
	    "IL"=>"Israel",
	    "IT"=>"Italy",
	    "JM"=>"Jamaica",
	    "JP"=>"Japan",
	    "JE"=>"Jersey",
	    "JO"=>"Jordan",
	    "KZ"=>"Kazakhstan",
	    "KE"=>"Kenya",
	    "KI"=>"Kiribati",
	    "KP"=>"Korea, Democratic People's Republic of",
	    "KR"=>"Korea, Republic of",
	    "KW"=>"Kuwait",
	    "KG"=>"Kyrgyzstan",
	    "LA"=>"Lao People's Democratic Republic",
	    "LV"=>"Latvia",
	    "LB"=>"Lebanon",
	    "LS"=>"Lesotho",
	    "LR"=>"Liberia",
	    "LY"=>"Libyan Arab Jamahiriya",
	    "LI"=>"Liechtenstein",
	    "LT"=>"Lithuania",
	    "LU"=>"Luxembourg",
	    "MO"=>"Macao",
	    "MK"=>"Macedonia, The Former Yugoslav Republic of",
	    "MG"=>"Madagascar",
	    "MW"=>"Malawi",
	    "MY"=>"Malaysia",
	    "MV"=>"Maldives",
	    "ML"=>"Mali",
	    "MT"=>"Malta",
	    "MH"=>"Marshall Islands",
	    "MQ"=>"Martinique",
	    "MR"=>"Mauritania",
	    "MU"=>"Mauritius",
	    "YT"=>"Mayotte",
	    "MX"=>"Mexico",
	    "FM"=>"Micronesia, Federated States of",
	    "MD"=>"Moldova",
	    "MC"=>"Monaco",
	    "MN"=>"Mongolia",
	    "ME"=>"Montenegro",
	    "MS"=>"Montserrat",
	    "MA"=>"Morocco",
	    "MZ"=>"Mozambique",
	    "MM"=>"Myanmar",
	    "NA"=>"Namibia",
	    "NR"=>"Nauru",
	    "NP"=>"Nepal",
	    "NL"=>"Netherlands",
	    "AN"=>"Netherlands Antilles",
	    "NC"=>"New Caledonia",
	    "NZ"=>"New Zealand",
	    "NI"=>"Nicaragua",
	    "NE"=>"Niger",
	    "NG"=>"Nigeria",
	    "NU"=>"Niue",
	    "NF"=>"Norfolk Island",
	    "MP"=>"Northern Mariana Islands",
	    "NO"=>"Norway",
	    "OM"=>"Oman",
	    "PK"=>"Pakistan",
	    "PW"=>"Palau",
	    "PS"=>"Palestinian Territory, Occupied",
	    "PA"=>"Panama",
	    "PG"=>"Papua New Guinea",
	    "PY"=>"Paraguay",
	    "PE"=>"Peru",
	    "PH"=>"Philippines",
	    "PN"=>"Pitcairn",
	    "PL"=>"Poland",
	    "PT"=>"Portugal",
	    "PR"=>"Puerto Rico",
	    "QA"=>"Qatar",
	    "RE"=>"Réunion",
	    "RO"=>"Romania",
	    "RU"=>"Russian Federation",
	    "RW"=>"Rwanda",
	    "BL"=>"Saint Barthélemy",
	    "SH"=>"Saint Helena",
	    "KN"=>"Saint Kitts and Nevis",
	    "LC"=>"Saint Lucia",
	    "MF"=>"Saint Martin",
	    "PM"=>"Saint Pierre and Miquelon",
	    "VC"=>"Saint Vincent and the Grenadines",
	    "WS"=>"Samoa",
	    "SM"=>"San Marino",
	    "ST"=>"Sao Tome and Principe",
	    "SA"=>"Saudi Arabia",
	    "SN"=>"Senegal",
	    "RS"=>"Serbia",
	    "SC"=>"Seychelles",
	    "SL"=>"Sierra Leone",
	    "SG"=>"Singapore",
	    "SK"=>"Slovakia",
	    "SI"=>"Slovenia",
	    "SB"=>"Solomon Islands",
	    "SO"=>"Somalia",
	    "ZA"=>"South Africa",
	    "GS"=>"South Georgia and the South Sandwich Islands",
	    "ES"=>"Spain",
	    "LK"=>"Sri Lanka",
	    "SD"=>"Sudan",
	    "SR"=>"Suriname",
	    "SJ"=>"Svalbard and Jan Mayen",
	    "SZ"=>"Swaziland",
	    "SE"=>"Sweden",
	    "CH"=>"Switzerland",
	    "SY"=>"Syrian Arab Republic",
	    "TW"=>"Taiwan, Province of China",
	    "TJ"=>"Tajikistan",
	    "TZ"=>"Tanzania, United Republic of",
	    "TH"=>"Thailand",
	    "TL"=>"Timor-Leste",
	    "TG"=>"Togo",
	    "TK"=>"Tokelau",
	    "TO"=>"Tonga",
	    "TT"=>"Trinidad and Tobago",
	    "TN"=>"Tunisia",
	    "TR"=>"Turkey",
	    "TM"=>"Turkmenistan",
	    "TC"=>"Turks and Caicos Islands",
	    "TV"=>"Tuvalu",
	    "UG"=>"Uganda",
	    "UA"=>"Ukraine",
	    "AE"=>"United Arab Emirates",
	    "GB"=>"United Kingdom",
	    "US"=>"United States",
	    "UM"=>"United States Minor Outlying Islands",
	    "UY"=>"Uruguay",
	    "UZ"=>"Uzbekistan",
	    "VU"=>"Vanuatu",
	    "VE"=>"Venezuela",
	    "VN"=>"Viet Nam",
	    "VG"=>"Virgin Islands, British",
	    "VI"=>"Virgin Islands, U.S.",
	    "WF"=>"Wallis and Futuna",
	    "EH"=>"Western Sahara",
	    "YE"=>"Yemen",
	    "ZM"=>"Zambia",
	    "ZW"=>"Zimbabwe"	
	);


	public function beforeFilter(){
		parent::beforeFilter();
		$this->Auth->autoRedirect = false;
		$this->Auth->fields = array('username' => 'email', 'password' => 'password');
	}
	
	/**
	 * 
	 * Add new product to Cart
	 */
	function cart_add(){
		if (empty($this->data)) {
			$this->Session->setFlash(__d('store','Invalid id for store order', true));
			$this->redirect($this->referer());
		}		
		
		$product = $this->StoreProduct->read(null, $this->data['StoreProduct']['id']);		
		$types = array();
		
		if(isset($this->data['StoreTypeGroup'])){
			// znajdz tylko zaznaczone	
			foreach ($this->data['StoreTypeGroup'] as $group => $type_id) {
				if($type_id['id'] != 0){
					$types['StoreType'][$type_id['id']]['id'] = $type_id['id'];
					$types['StoreType'][$type_id['id']]['name'] = $this->data['StoreType'][$type_id['id']]['name'];
					$types['StoreType'][$type_id['id']]['amount'] = $this->data['StoreType'][$type_id['id']]['amount'];
					$types['StoreType'][$type_id['id']]['group'] = $this->data['StoreType'][$type_id['id']]['group'];
				}
			}
		}
			if(isset($types['StoreType']) && count($types['StoreType']) == count($this->data['StoreTypeGroup'])){	
				$product['StoreType'] = (isset($types['StoreType'])) ? $types['StoreType'] : arry();
				$product['StoreProduct']['amount'] = 1;
				$this->Session->write('Store.Cart.Items.'.$this->data['StoreProduct']['id'],$product);
				$this->redirect(array('plugin'=>'store','controller'=>'carts','action'=>'cart_view'));
			}else if(isset($types['StoreType']) && count($types['StoreType']) > count($this->data['StoreTypeGroup'])) {
				$this->Session->setFlash(sprintf(__d('store','You can add more that %s types', true),count($this->data['StoreTypeGroup'])));
			}else if(!isset($types['StoreType'])){
				$product['StoreProduct']['amount'] = 1;
				$this->Session->write('Store.Cart.Items.'.$this->data['StoreProduct']['id'],$product);
				$this->redirect(array('plugin'=>'store','controller'=>'carts','action'=>'cart_view'));
				
			}else{
				$this->Session->setFlash(__d('store','Please select all type of product', true));
			}
		
		$this->redirect($this->referer());
	}

	/**
	 * 
	 * Display order to edit
	 */
	function cart_view(){
		if (!empty($this->data)) {
			foreach ($this->data['StoreProduct'] as $product_id => $amount) {
				$inventory = $this->StoreProduct->field('StoreProduct.stan',array('StoreProduct.id'=>$product_id));
				$service = $this->StoreProduct->field('StoreProduct.service',array('StoreProduct.id'=>$product_id));
				if($inventory >= $amount['amount'] || $service){
					$this->Session->write("Store.Cart.Items.{$product_id}.StoreProduct.amount",$amount['amount']);	
				}else{
					$this->Session->setFlash(sprintf(__d("store","Max inventory is %s", true),$inventory));
					$this->Session->write("Store.Cart.Items.{$product_id}.StoreProduct.amount",$inventory);
					$this->redirect(array('plugin'=>'store','controller'=>'carts','action'=>'cart_view'));
				}
			}
			if(Configure::read('Config.DeliveryType') == 'by-quantity'){
				$this->redirect(array('plugin'=>'store','controller'=>'carts','action'=>'cart_verification'));
			}else{		
				$delivery['name'] = 'Delivery';
				$delivery['price'] = 3.50;
				$delivery['currency_id'] = 'GBP';
				$delivery['exchange'] = null;		
				$this->Session->write('Store.Cart.Delivery',$delivery);
				$this->redirect(array('plugin'=>'store','controller'=>'carts','action'=>'cart_customer'));
			}
		}		
		
		$items = $this->Session->read('Store.Cart.Items');
		$ilosc_razem = count($items);
		$this->set(compact('items','ilosc_razem'));
		
//		debug($this->Session->read("Store.Cart.Items"));
		$this->layout = 'default';
	}	
	
	/**
	 * 
	 * Display order for verefication
	 */
	function cart_verification(){	
		if (!empty($this->data)) {
			if(isset($this->data['StoreDelivery']['selected']['id']) && is_numeric($this->data['StoreDelivery']['selected']['id'])){
				$this->Session->write('Store.Cart.Delivery',$this->data['StoreDelivery'][$this->data['StoreDelivery']['selected']['id']]);
				$this->redirect(array('plugin'=>'store','controller'=>'carts','action'=>'cart_customer'));
			}else{
				$this->Session->setFlash(__d("store","Please select delivery costs", true));
			}
		}	
		
      
		$items = $this->Session->read('Store.Cart.Items');
		$ilosc_razem = 0;
		foreach ($items as $item) {				
			foreach ($item['StoreType'] as $type) {
				$ilosc_razem += $type['amount'];
			}
		}		
		$storeDeliveries = $this->StoreDelivery->find('all');
		$this->set(compact('storeDeliveries','items','ilosc_razem'));
		$this->layout = 'default';
	}
	
	function cart_select_payment(){
		

	}
	
	/**
	 * 
	 * Save order and send to realisation
	 */
	function cart_send(){
		if (!empty($this->data)) {
			if($this->_add_order()){
				if($this->_send()){							
					$this->Session->setFlash(__d("store","The store order has been send and saved", true));
					$this->Session->delete('Store.Cart');					
					$this->redirect(array('plugin'=>'store','controller'=>'products','action'=>'display'));
				}else{
					$this->Session->setFlash(__d("store","The store order could not be sendd. Please, contact by phone or e-mail with store administrator.", true));
					$this->Session->delete('Store.Cart');
					$this->redirect(array('plugin'=>'store','controller'=>'carts','action'=>'cart_view'));
				}				
				
			}		
		}	
	}
	
	private function _add_order(){
		$items = $this->Session->read('Store.Cart.Items');
		$delivery = $this->Session->read('Store.Cart.Delivery');
		if (!empty($items) && is_array($items) && count($items) >= 1) {
			
			$this->transaction->begin($this);
			
			$this->data['StoreOrder']['user_id'] = $this->Auth->user('id');
			$this->data['StoreOrder']['added'] = date('Y-m-d H:i:s');
			$this->data['StoreOrder']['status'] = 1;
			
			$this->StoreOrder->create();
			if ($this->StoreOrder->save($this->data)) {
				try{
					$order_id = $this->StoreOrder->getLastInsertID();
					$this->Session->write('Store.Cart.Order.id',$order_id);
					
					$this->data['StoreOrderDelivery']['order_id'] = $order_id;
					$this->data['StoreOrderDelivery']['name'] = $delivery['name'];
					$this->data['StoreOrderDelivery']['price'] = $delivery['price'];
					$this->data['StoreOrderDelivery']['currency_id'] = $delivery['currency_id'];
					$this->data['StoreOrderDelivery']['exchange'] = $delivery['exchange'];
					
					$this->StoreOrderDelivery->create();
					$this->StoreOrderDelivery->save($this->data);
					
					$this->data['StoreOrderDetail']['order_id'] = $order_id;					
					foreach ($items as $key => $item) {
						$this->data['StoreOrderDetail']['user_id'] = $this->Auth->user('id');
						$this->data['StoreOrderDetail']['product_id'] = $item['StoreProduct']['id'];
						$this->data['StoreOrderDetail']['currency_id'] = $item['StoreProduct']['currency_id'];
						
						$this->data['StoreOrderDetail']['tax_id'] = $item['StoreProduct']['tax_id'];
						$this->data['StoreOrderDetail']['unit_id'] = $item['StoreProduct']['unit_id'];
						$this->data['StoreOrderDetail']['exchange'] = $item['StoreCurrency']['exchange'];
						
						foreach ($item['StoreType'] as $type_id => $type){
							$this->data['StoreOrderDetail']['type_id'] = $type_id;
							$this->data['StoreOrderDetail']['ilosc'] = $type['amount'];
							$this->StoreOrderDetail->create();
							if ($this->StoreOrderDetail->save($this->data)){
								
								$inventory = $this->StoreProductType->field('inventory',
									array('StoreProductType.product_id'=>$this->data['StoreOrderDetail']['product_id'],'StoreProductType.type_id'=>$type_id));
								$inventory = $inventory - $type['amount'];
								if($inventory == 0){
									if (!$this->StoreProductType->deleteAll(array('StoreProductType.product_id'=>$this->data['StoreOrderDetail']['product_id'],'StoreProductType.type_id'=>$type_id))){
										$this->transaction->rollback($this);
										return false;	
									}
								} else if (!$this->StoreProductType->updateAll(array('StoreProductType.inventory'=>$inventory),
												array('StoreProductType.product_id'=>$this->data['StoreOrderDetail']['product_id'],'StoreProductType.type_id'=>$type_id))){
									$this->transaction->rollback($this);
									return false;
								}
							}else{									
								$this->transaction->rollback($this);
								return false;
							}
						}						
					}
				}catch (Exception $e){
					$this->transaction->rollback($this);
					return false;
				}
				
				$this->transaction->commit($this);
				return true;
			}
			$this->transaction->rollback($this);
			return false;
		}
	}
	
    private function _send(){
    	// adresy odbiorcow zamowienia
    	$manag = $this->User->find('list',array('fields'=>'email','conditions'=>array('User.group'=>"manag"))); // moderators
    	if(is_array($manag) && !empty($manag)){
    	}else{
    		$manag = $this->User->find('list',array('fields'=>'email','conditions'=>array('User.group'=>"admin")));
    	}
    	
        $sprzedawca = $this->User->find('first',array('conditions'=>array('User.group'=>"manag"))); // moderators
    	if(is_array($sprzedawca) && !empty($sprzedawca)){
    	}else{
    		$sprzedawca = $this->User->find('first',array('conditions'=>array('User.group'=>"admin")));
    	}    	
    	
    	// odbiorca
    	if($this->Session->check('Auth.User.id')){
			$customer = $this->Session->read('User.Customer.0');
			$employee = $this->Session->read('User.Employee.0');
			if(!is_array($customer) || empty($customer)){
				$customer = $employee;
			}
		}
    	
    	$items = $this->Session->read('Store.Cart.Items');
    	$delivery = $this->Session->read('Store.Cart.Delivery');
    	
    	
    	$ilosc_razem = 0;
		foreach ($items as $item) {				
			foreach ($item['StoreType'] as $type) {
				$ilosc_razem += $type['amount'];
			}
		}	    	
    	$this->set(compact('items','delivery','ilosc_razem','sprzedawca','customer'));
    	
//    	$this->Email->delivery = 'debug';
        $this->Email->to = $this->Session->read('Auth.User.email'); 
        $this->Email->bcc = $manag;
        $this->Email->subject = __d("store","Zamowienie Nr ",true).$this->Session->read('Store.Cart.Order.id').' - '.$_SERVER['HTTP_HOST']; 
        $this->Email->from = $_SERVER['HTTP_HOST']." <{$_SERVER['HTTP_HOST']}>"; 
        $this->Email->template = "plugin-store-order"; 
        $this->Email->sendAs = 'both'; // text; html; both;
 			
        //Do not pass any args to send() 
        if ( $this->Email->send() ) { 
             return true;
        } else { 
            return false; 
        }     
    }
	
	function cart_end(){
		$this->layout = 'default';
	}
	
	/**
	 * 
	 * Display Customre / login or register
	 */
	function cart_customer(){
		if($this->Session->check('Auth.User.id') && !empty($this->data)){
			$this->Customer->set( $this->data );
			if ($this->Customer->validates()) {
				$user = $this->User->findById($this->Auth->user('id'));
		    	$this->Session->write("User",$user);
		    	$this->redirect(array('plugin'=>'sage_pay','controller'=>'payment','action'=>'confirm'));
			}else{
				$this->Session->setFlash(__d('store','The new customer could not be saved. Please, try again.', true));
//				$this->redirect(array('plugin'=>'store','controller'=>'carts','action'=>'cart_customer'));
			}
		}
		if (!empty($this->data) && !$this->Session->check('Auth.User.id')) {
				$this->transaction->begin($this);
				
				$this->data['User']['email'] = $this->data['Customer']['email'];
				$password = $this->Password->get();	// nie zaszyfrowane hasło do wysłania klientowi
				$this->data['User']['password'] =  $this->Auth->password($password);	
				$this->data['User']['status'] = 1;
				$this->data['User']['group'] = 'firms';
				$this->Customer->set( $this->data );
				if ($this->Customer->validates()) {
							
					$this->User->create();
					if ($this->User->save($this->data)) {
						$this->data['Customer']['user_id'] = $this->User->getLastInsertID();
						$this->data['Customer']['registration_date'] = date('Y-m-d H:i:s');
						$this->User->Customer->create();
						if ($this->User->Customer->save($this->data)) {
							
	    					$user_['User']['email'] = $this->data['User']['email'];
	    					$user_['User']['password'] = $this->data['User']['password'];
	    					
	    					if($this->Auth->login($user_)){
	    						$user = $this->User->findById($this->Auth->user('id'));
	    						$this->Session->write("User",$user);
	    					}
	    					$this->transaction->commit($this);
	    					$this->Session->setFlash(__d('store','The customer has been saved', true));
							$this->redirect(array('plugin'=>'sage_pay','controller'=>'payment','action'=>'confirm'));
						} else {
							$this->Session->setFlash(__d('store','The customer could not be saved. Please, try again.', true));
							$this->transaction->rollback($this);
						}
					} else {
						$this->Session->setFlash(__d('store','The customer could not be saved. Please, try again.', true));
						$this->transaction->rollback($this);
					}
	
				} else {
					$this->Session->setFlash(__d('store','The customer could not be saved. Please, try again.', true));
					$this->transaction->rollback($this);
				}	
		
		}
		if($this->Session->check('Auth.User.id')){
			$customer = $this->Session->read('User.Customer.0');
			$employee = $this->Session->read('User.Employee.0');
			if(is_array($customer) && !empty($customer)){
				$this->data['Customer'] = $customer;
			}else if(is_array($employee) && !empty($employee)){
				$this->data['Customer'] = $employee;
			}else{
				$this->data['Customer'] = $this->Session->read('User.Customer.0');
			}
		}
		$this->set('countrycod',$this->countrycod);
	}
	
	function login(){
		if(!empty($this->data)){
			if($this->Auth->login($this->data)){
    			$user = $this->User->findById($this->Auth->user('id'));
    			$this->Session->write("User",$user);
    		}
			$this->redirect(array('plugin'=>'store','controller'=>'carts','action'=>'cart_customer'));
		}
	}
	
	/**
	 * 
	 * Clear all order
	 */
	function cart_clear(){
		$this->Session->delete('Store.Cart.Items');
		$this->Session->delete('Store.Cart.Delivery');
		$this->redirect($this->referer());
	}
	
	/**
	 * 
	 * Delete One Type from product in order
	 * @param $product_id
	 * @param $type_id
	 */
	function cart_delete_type($product_id,$type_id){
		$this->Session->delete("Store.Cart.Items.{$product_id}.StoreType.{$type_id}");
		$types = $this->Session->read("Store.Cart.Items.{$product_id}.StoreType");
		if(count($types) == 0) $this->cart_delete($product_id);
		$this->redirect($this->referer());
	}
	
	/**
	 * 
	 * Delete One product from order
	 * @param $product_id
	 */
	function cart_delete($product_id){
		$this->Session->delete("Store.Cart.Items.{$product_id}");
		$this->redirect($this->referer());
	}	
}